window.onload = function () {
    /*初始化*/
    initFcsh()

    /* + 按钮事件 */
    $(".addConfig").click(function () {
        var elem = document.querySelector('.add-js-switch');
        if (elem) {
            showMsg("已存在一个编辑项")
        } else {
            var uid = uuid();
            addConfigInitHtml('default config name', uid, true, false, true);
            setTextArea('', uid)
        }
    });

    /*删除按钮点击事件*/
    $(".delConfig").click(function () {
        var leftTitleClick = $(".left-title-click");
        var targetUid = leftTitleClick.data('uid')
        if (targetUid && targetUid !== 0) {
            // 删除缓存
            delCache(targetUid)
            // 删除自身元素
            leftTitleClick.remove()
            // 更新root hosts
            updateRootContent(targetUid)
            showMsg('删除成功')
        }
    });

    /*保存按钮点击事件*/
    $(".saveConfig").click(function () {
        var uid = $(this).data('uid');
        if (uid !== "0") {
            var content = $(".contentConfig").val();
            var error = validate(content)
            if (error) {
                showMsg(error)
            } else {
                var config = getCache(uid);
                config.content = content
                // 更新缓存
                updateCache(uid, config)
                // 更新root hosts content
                updateRootContent(uid, true)
                showMsg('设置代理成功')
            }
        }
    });
}

/**
 * 校验配置
 * @param value
 * @returns {null}
 */
function validate(value) {
    var rules = value.trim().replace(/#.+/gm, '').split('\n')
    var error = null
    rules.forEach(rule => {
        let r = rule.split(/\s+/)
        if (r.length < 2) {
            error = '请输入正确的格式'
        }
        if (isProxy(r[0])) {
            error = '请输入正确的格式'
        }
        if (r[0].indexOf(':') > 0) {
            error = '请输入正确的格式'
        }

        if (!isIP(r[0])) {
            error = 'ip 格式不正确.'
        }
        r.shift()
        if (r.length) {
            r.filter(h => h.trim() !== '').forEach(h => {
                let isValidHost = isDomain(h) || isLocalHost(h)
                if (!isValidHost) {
                    error = `域名 [${r}] 格式不正确.`
                }
            })
        }
    })
    return error
}

/**
 * 添加配置初始化 html页面
 * @param str 配置名称
 * @param uid 唯一标识
 * @param check 是否选中
 * @param isRoot 是否是初始化 root
 * @param addTitle 是否是添加
 */
function addConfigInitHtml(str, uid, check, isRoot, addTitle) {
    var html =
        '<span title="' + str + '" data-uid="' + uid + '" class="text-title ' + uid + '" style="' + (addTitle ? 'display: none;' : 'display: inline-block;') + '">' + str + '</span>'
        + '<input data-uid="' + uid + '" class="init-edit-input-' + uid + ' input-sm titleConfigName ' + uid + '" type="text" value="' + (str ? str : 'default config name') + '" style="' + (addTitle ? 'display: inline-block;' : 'display: none;') + '">';
    var leftTitleHtml =
        '<div class="init-title-click-' + uid + ' left-title to-hand one-left-title ' + (isRoot ? 'left-title-click' : '') + '" data-uid="' + uid + '">' +
        '    <input type="checkbox" class="init-switch-' + uid + ' js-switch " ' + (check ? 'checked' : '') + ' data-uid="' + uid + '"/>' +
        '    ' + html +
        '    <div class="float-right" style="' + (isRoot ? 'display: none;' : 'display: inline-block;') + '">' +
        '        <i class="fa fa-edit edit-fa edit-fa-' + uid + '" data-uid="' + uid + '"></i>' +
        '    </div>' +
        '</div>';
    $(".left-titles").append(leftTitleHtml)
    addConfigInitEvent(uid)
}

function addConfigInitEvent(uid) {
    /*配置文件名字输入框失去焦点事件*/
    $(".init-edit-input-" + uid).blur(function () {
        $("input." + uid).hide();
        var name = $(this).val();
        saveLeftTitle($(this).val(), $(this).data('uid'))
        $("span." + uid).text(name).show();
    });
    /*左侧列表点击*/
    $(".init-title-click-" + uid).click(function (e) {
        $(".left-title-click").removeClass('left-title-click');
        var uid = $(this).addClass('left-title-click').data('uid')
        var title = getCache(uid)
        if (title) {
            setTextArea(title.content, uid)
        }
    });
    /*初始化开关组件*/
    var elem = document.querySelector(".init-switch-" + uid);
    new Switchery(elem, {color: '#4ec54e', width: '20px', height: '20px'});
    /*开关按钮绑定change事件*/
    $(".init-switch-" + uid).on('change', function () {
        var status = $(this).prop("checked");
        var uid = $(this).data('uid');
        var title = getCache(uid);
        title.check = status
        updateCache(uid, title)
        updateRootContent(uid, status)

    })
    /*编辑按钮点击事件*/
    $(".edit-fa-" + uid).click(function () {
        var uid = $(this).data('uid')
        $("span." + uid).hide();
        $("input." + uid).show().focus();
    });
}

/**
 * 左侧input框 失去焦点事件
 * @param str
 * @param uid
 */
function saveLeftTitle(str, uid) {
    var check = $(".init-switch-" + uid).removeClass('add-js-switch').prop("checked");
    var title = getCache(uid) || {check: check, name: str, uid: uid, content: ''}
    title.check = check;
    title.name = str;
    title.uid = uid;
    setCache(uid, title)
}

/**
 * 设置文本框
 */
function setTextArea(str, uid) {
    var contentConfig = $(".contentConfig");
    if (uid !== 0) {
        contentConfig.removeAttr('readonly')
        contentConfig.val(str)
    } else {
        contentConfig.attr('readonly', "readonly")
        var vs = [];
        $.each(str, function (k, v) {
            vs.push(v)
        })
        contentConfig.val(vs.join("\n"))
    }
    $(".saveConfig").data('uid', uid)
}

/**
 * 消息提示
 * @param msg
 */
function showMsg(msg) {
    $(".msg").text(msg).show();
    window.setTimeout(function () {
        $(".msg").text(msg).hide();
    }, 1000);
}

function uuid() {
    var index = getCache("index");
    updateCache("index", index + 1)
    return index;
}

/**
 * 初始化
 */
function initFcsh() {
    /*初始化缓存*/
    initCahce()
    /*初始化右侧的leftTitles*/
    var titles = getAllCache();
    $.each(titles, function (uid, title) {
        if (uid !== 'index') {
            addConfigInitHtml(title.name, title.uid, title.check, title.uid === 0, false)
        }
    })
    /*初始化文本框的值*/
    var title = titles[0];
    var rootContent = []
    $.each(title.content, function (k, v) {
        rootContent.push(v)
    })
    $(".contentConfig").val(rootContent.join('\n'))
}
